﻿using CPPEI.Coolzon.Common.Startup;
using CPPEI.Coolzon.Configuration;
using CPPEI.Coolzon.UI;
using CPPEI.WPF.Core;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace CPPEI.Coolzon.DisplayApp
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : XApplication
    {
        private PerformanceMonitorThread _pfmThread;
        public App()
            : base("CPPEI", "Coolzon", "DisplayApp", "展示器", "Launcher")
        {
            Common.Logger.InitByLogDirectory(CZEnvironment.GetLogDirectory());
            // 初始化配置信息
            XConfigUtil.Init(CZEnvironment.Instance, CZEnvironment.GetEnvironmentFilePath());
            XConfigUtil.Init(CPPEI.Coolzon.UI.Settings.Instance, CZEnvironment.GetSettingsFilePath());

            System.Windows.Application.Current.DispatcherUnhandledException += App_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            Settings.IsSingleton = true;

            // 启动性能监控线程
            _pfmThread = new PerformanceMonitorThread();
            _pfmThread.Start();

        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                if (e.ExceptionObject is Exception)
                {
                    Common.Logger.ErrorToTag(this.GetType().ToString(), "未捕获的异常{0}", e.ExceptionObject.ToString());
                }
            }
            catch (Exception ex)
            {
                Common.Logger.ErrorToTag(this.GetType().ToString(), "未捕获的异常{0}", ex);
            }
        }

        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                Common.Logger.ErrorToTag(this.GetType().ToString(),"未捕获的异常{0}",e.Exception);
                e.Handled = true;
            }
            catch (Exception ex)
            {
                Common.Logger.ErrorToTag(this.GetType().ToString(), "未捕获的异常{0}", ex);
            }
        }

        protected override void OnXStartup(StartupParamCollection startupParams)
        {
            Common.Logger.InfoToTag("APP", "应用程序启动!");

            // 启动激光笔程序
            CPPEI.Coolzon.DisplayApp.ExternalApp.LaserPointApp.Run();

            //Common.Logger.InfoToTag("APP", string.Format("应用程序启动,RenderCapability.Tier:{0}!", System.Windows.Media.RenderCapability.Tier));

            //Common.Logger.InfoToTag("APP", "关闭硬件加速");
            //System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;


            App.Current.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;

            //检测更新窗体
            SplashWindow splashWindow = new SplashWindow(startupParams.IsCheckVersion,App.XCurrent.AppInfo, CZEnvironment.Instance.UpdateServiceConfig);
            splashWindow.ShowDialog();
            if (!splashWindow.IsContinueRunning)
            {
                return;
            }
            else
            {
                App.Current.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
            }

            // 初始化数据缓存目录
            CPPEI.Coolzon.DataTask.DataResultCache.Init(CZEnvironment.GetDataCacheDirectory());

            CPPEI.Coolzon.Configuration.Client.Config.InitHostConfig(CZEnvironment.GetHostConfigFilePath());
            // 初始化备用服务器的配置信息
            CPPEI.Coolzon.Configuration.Client.Config.InitSpareHostConfig(CZEnvironment.GetSpareHostConfigFilePath());

            CPPEI.Coolzon.Configuration.Client.Config.InitPartLibsConfig(CZEnvironment.GetPartLibConfigFilePath());
            CPPEI.Coolzon.Configuration.Client.Config.PartLibs.PartLibsBaseAddress = AppDomain.CurrentDomain.BaseDirectory;

            // 初始化属性的转换器和编辑器配置信息
            CPPEI.Coolzon.UI.XProperty.PropertyValueConverterFactory.Init(string.Format("{0}\\Config\\XProperty.xml",
                AppDomain.CurrentDomain.BaseDirectory));
           
            //初始化事件代理
            ServiceProxy.MainServiceRef.MainServiceClient client = ServiceProxy.ProxyFactory.InitMainServiceClient(RemoteEventProxy.Instance);
            RemoteEventProxy.Instance.SetMainServiceClient(client);

            UIContext.Current.AppStartupPath = AppDomain.CurrentDomain.BaseDirectory;
            UIContext.Current.AppType = "DisplayApp";
            UIContext.Current.AppVersion = CZEnvironment.Version4;
            UIContext.Current.OSVersion = System.Environment.OSVersion.Version.ToString();
            UIContext.Current.DotNetVersion = System.Environment.Version.ToString();
            // 设置事件处理模式
            UIContext.Current.EventProcessMode = UI.Views.EventProcessMode.UnderControl;
            UIContext.Current.IsShowActiveXPart = CZEnvironment.Instance.IsShowActiveXPart;

            StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);

            // 启动激光笔程序
            CPPEI.Coolzon.DisplayApp.ExternalApp.LaserPointApp.Run();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            CPPEI.Coolzon.DisplayApp.ExternalApp.LaserPointApp.Instance.Close();

            ExeServiceManager.Release();
            // 释放预加载的内容（可能有外部程序)
            UI.Views.PreloadModule.Release();

            if (_pfmThread != null)
            {
                _pfmThread.Stop();
            }
            try
            {
                Service.Contract.ReqLogoutData requestData = new Service.Contract.ReqLogoutData();
                requestData.UserIdentity = UIContext.Current.UserIdentity;

                ServiceProxy.ClientProxyManager.Instance.SendRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    Service.Contract.REQUEST_SCENARIO.CONNENT,
                    Service.Contract.REQUEST_COMMAND.CONNECT.LOGOUT,
                    Service.Contract.REQUEST_MODE.NORESPONSE,
                    requestData);
            }
            catch (Exception ex)
            {
                Common.Logger.ErrorToTag("UI", "退出登录失败!{0}", ex);
            }

            base.OnExit(e);
        }
    }
}
